package com.fjh.security.easy.starter.authentication.service.impl;

import com.fjh.security.easy.starter.authentication.service.EasyAuthFailureService;
import com.fjh.security.easy.starter.config.EasyPropertiesConfig;
import es.moki.ratelimitj.core.limiter.request.RequestRateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author fanjh37
 * @since 2023/2/6 22:46
 */
@Slf4j
public class EasyDefaultAuthFailureServiceImpl implements EasyAuthFailureService {


    @Autowired
    private RequestRateLimiter requestRateLimiter;

    @Autowired
    private EasyPropertiesConfig easyPropertiesConfig;

    @Override
    public void authenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        String key = httpServletRequest.getParameter("username");
        //计数器加1，并判断该用户是否已经到了触发了锁定规则
        if (e instanceof BadCredentialsException) {
           if(requestRateLimiter.overLimitWhenIncremented(key)) {
               log.error("用户{}多次登录密码错误被锁定{}小时", key, easyPropertiesConfig.getLock().getTimeOut());
           }
        }
    }
}
